<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import http from "@/utils/request";
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "./mixins/resize";

const animationDuration = 6000;

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "300px",
    },
  },
  mounted() {
    http.get(`/dashboard`).then((res) => {
      res.data.data.hotProduct.forEach((e) => {
        this.productCategory.push(e.name);
        this.productTotalSales.push(e.totalSales);
      });
      this.$nextTick(() => {
        this.initChart();
      });
    });
  },
  data() {
    return {
      chart: null,
      productCategory: [],
      productTotalSales: [],
    };
  },

  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, "macarons");

      this.chart.setOption({
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        grid: {
          top: 10,
          left: "2%",
          right: "2%",
          bottom: "3%",
          containLabel: true,
        },
        title: [
          {
            subtext: "单位（元）",
            left: 43, // 距离左边位置
            top: -15, // 距离上面位置
            subtextStyle: {
              // 设置二级标题的样式
              color: "#baf",
            },
          },
          {
            text: "热销商品排行榜",
            left: 300, // 距离左边位置
            top: -3, // 距离上面位置
            subtextStyle: {
              // 设置一级标题的样式
              color: "#baf",
            },
          },
        ],
        xAxis: {
          type: "category",
          name: "产品类别",
          data: this.productCategory,
          axisTick: {
            alignWithLabel: true,
          },
        },
        yAxis: {
          type: "value",
          name: "单位（元）",
          nameTextStyle: {
            color: "#aaa",
            nameLocation: "start",
          },
          axisTick: {
            show: false,
          },
        },
        series: [
          {
            name: "总销售额",
            type: "bar",
            stack: "vistors",
            barWidth: "60%",
            data: this.productTotalSales,
            animationDuration,
          },
        ],
      });
    },
  },
};
</script>
